/* eslint-disable standard/object-curly-even-spacing,no-unused-vars */
import express, { Router } from 'express'

let fs = require('fs')

const app = express()
const router = Router()
// 上传模块
const multer = require('multer')
// 实例化上传模块(前端使用参数名为file)
// const upload = multer({dest: 'static/uploads/'})

let createFolder = function (folder) {
  try {
    fs.accessSync(folder)
  } catch (e) {
    fs.mkdirSync(folder)
  }
}

let uploadFolder = 'static/uploads/'

createFolder(uploadFolder)

// 通过 filename 属性定制 http://www.cnblogs.com/wteam-xq/p/4316832.html
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let path = uploadFolder + req.query.q
    createFolder(path)
    path = uploadFolder + req.query.q + '/' + new Date().toLocaleDateString()
    createFolder(path)
    cb(null, path) // 保存的路径，备注：需要自己创建
  },
  filename: function (req, file, cb) {
    // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
    // let pos = file.originalname.lastIndexOf('.')
    // let firstName = file.originalname.substring(0, pos)
    // let lastName = file.originalname.substring(pos + 1)
    // cb(null, file.fieldname + '_' + Date.now() + '.' + lastName)
    cb(null, file.originalname)
    // cb(null, file.originalname)
  }
})

function fileFilter (req, file, cb) {
  // The function should call `cb` with a boolean
  // to indicate if the file should be accepted

  // To reject this file pass `false`, like so:
  if (file.mimetype === 'application/zip') {
    cb(null, false)
    cb(new Error('不支持文件类型'))
  }

  // To accept the file pass `true`, like so:
  if (file.mimetype === 'text/plain') {
    cb(null, true)
  }
  // You can always pass an error if something goes wrong:
  // cb(new Error('I don\'t have a clue!'))
}

// 通过 storage 选项来对 上传行为 进行定制化
let upload = multer({ storage: storage })
// let upload = multer({ storage: storage, fileFilter: fileFilter, limits: {fileSize: 100000000}}) // 100M

// form-data key:logo
app.post('/upload', upload.single('file'), function (req, res, next) {
  if (req.file === undefined) {
    res.send({ message: 'no file' })
    return
  }
  let file = req.file
  console.log('文件类型：%s', file.mimetype)
  console.log('原始文件名：%s', file.originalname)
  console.log('文件大小：%s', file.size)
  console.log('文件保存路径：%s', file.path)
  res.send(
    Object.assign(file,
      {
        url: file.path.replace(/\\/g, '/').substring(6)
      }))
})

app.post('/uploadMul', upload.array('file', 10), function (req, res, next) {
  console.log(req.files[0].originalname)
  res.send({ fileList: req.files })
})

app.post('/del', function (req, res, next) {
  console.log('delete file')
  console.log(req.body.path)
  fs.unlinkSync(req.body.path)
  res.json({ 'delete': 'ok' })
})

export default app
